<meta charset="UTF-8">
<style>
    #batchadddevice div.full>div {
        width: 700px;
        margin: 0 auto;
    }
    
    #batchadddevice .ivu-select-dropdown-list {
        max-height: 300px;
    }
    
    #batchadddevice div.error textarea {
        color: red
    }
    
    #batchadddevice div.succ textarea {
        color: rgb(26, 160, 52);
    }
</style>
<div id="batchadddevice">
    <div class="full" style="padding:10px 10px 0 10px;">
        <h3 class="h3-title">{{$t("bgMgr.addDev")}}</h3>
        <div>
            <Row style="margin: 10px 0" v-if="userType < 4">
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;"><i style="color: red;display: inline-block;">*</i>&nbsp;{{$t("reportForm.selectAccount")}} : &nbsp;</i-col>
                <i-col span="8">
                    <el-select v-model="createrToUser" style="width: 100%;" size="mini" filterable>
                        <el-option v-for="item in userlists" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </i-col>
            </Row>
            <Row style="margin: 10px 0">
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t("user.grouping")}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-select v-model="groupid">
                        <i-option v-for="item in groupsList" :value="item.value" :key="item.value">{{ item.label }}</i-option>
                    </i-select>
                </i-col>
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;{{$t("device.networkType")}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-select v-model="teltype">
                        <i-option value="1">{{$t("reportForm.maxSignal")}}32(2G)</i-option>
                        <i-option value="2">{{$t("reportForm.maxSignal")}}64(2G)</i-option>
                        <i-option value="3">{{$t("reportForm.maxSignal")}}32(3G)</i-option>
                        <i-option value="4">{{$t("reportForm.maxSignal")}}32(4G)</i-option>
                    </i-select>
                </i-col>
            </Row>

            <Row style="margin: 10px 0">
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;"><i style="color: red;display: inline-block;">*</i>&nbsp;{{$t("user.devType")}} : &nbsp;</i-col>
                <i-col span="8">
                    <!-- devicetype -->
                    <el-select v-model="devicetype" style="width: 100%;" size="mini" filterable>
                        <el-option v-for="item in deviceTypeList" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </i-col>

                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;{{$t("bgMgr.expirenotifytime")}} : &nbsp;</i-col>
                <i-col span="8">
                    <date-picker type="date" v-model="overduetime" :options="dateOptions" style="width: 100%"></date-picker>
                </i-col>

            </Row>

            <Row style="margin: 10px 0">

                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t("device.allowLogin")}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-select v-model="loginenable">
                        <i-option value="0">{{$t("user.ban")}}</i-option>
                        <i-option value="1">{{$t("user.allow")}}</i-option>
                    </i-select>
                </i-col>
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t("device.isUse")}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-select v-model="deviceenable">
                        <i-option value="0">{{$t("user.ban")}}</i-option>
                        <i-option value="1">{{$t("user.allow")}}</i-option>
                    </i-select>
                </i-col>
            </Row>

            <Row style="margin: 10px 0">
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">{{$t("device.idLength")}}: &nbsp;</i-col>
                <i-col span="8">
                    <input-number v-model.number="idLength" :max="30" :min="8" style="width: 100%;"></input-number>
                </i-col>
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;{{$t("device.timeZone")}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-select v-model="timezone">
                        <i-option value="99">{{$t("device.automatic")}}</i-option>
                        <i-option value="-12">-12</i-option>
                        <i-option value="-11">-11</i-option>
                        <i-option value="-10">-10</i-option>
                        <i-option value="-9">-9</i-option>
                        <i-option value="-8">-8</i-option>
                        <i-option value="-7">-7</i-option>
                        <i-option value="-6">-6</i-option>
                        <i-option value="-5">-5</i-option>
                        <i-option value="-4">-4</i-option>
                        <i-option value="-3">-3</i-option>
                        <i-option value="-2">-2</i-option>
                        <i-option value="-1">-1</i-option>
                        <i-option value="0">0</i-option>
                        <i-option value="1">+1</i-option>
                        <i-option value="2">+2</i-option>
                        <i-option value="3">+3</i-option>
                        <i-option value="4">+4</i-option>
                        <i-option value="5">+5</i-option>
                        <i-option value="6">+6</i-option>
                        <i-option value="7">+7</i-option>
                        <i-option value="8">+8</i-option>
                        <i-option value="9">+9</i-option>
                        <i-option value="10">+10</i-option>
                        <i-option value="11">+11</i-option>
                        <i-option value="12">+12</i-option>
                        <i-option value="13">+13</i-option>
                        <i-option value="14">+14</i-option>
                    </i-select>
                </i-col>
            </Row>

            <Row style="margin: 10px 0">
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;{{$t("device.calmileageway")}} : &nbsp;</i-col>
                <i-col span="8">
                    <i-select v-model="calmileageway">
                        <i-option value="0">{{$t("device.automatic")}}</i-option>
                        <i-option value="1">{{$t("device.devCalc")}}</i-option>
                        <i-option value="2">{{$t("device.platformCalc")}}</i-option>
                    </i-select>
                </i-col>
            </Row>

            <Row style="margin: 10px 0">
                <i-col span="4" style="height: 100%;text-align:right;line-height:32px;">&nbsp;{{$t('alarm.devNum')}} : &nbsp;</i-col>
                <i-col span="6">
                    <i-input v-model.trim="deviceid" type="textarea" :placeholder="$t('device.copyBatchNumber')" :autosize="{minRows: 2,maxRows: 6}"></i-input>
                </i-col>

                <i-col span="13" :offset="1">
                    <i-input v-model.trim="errorTips" :class="fontColor" type="textarea" disabled :autosize="{minRows: 2,maxRows: 6}"></i-input>
                </i-col>
            </Row>

            <Row style="margin: 10px 0">
                <i-col span="20" :offset="4">
                    <Alert type="warning">
                        <h3>{{$t("device.addNewDeviceTip1")}}</h3>
                        <p v-if="isZh">
                            {{$t("device.addNewDeviceTip2")}}
                        </p>
                        <p v-if="isZh">
                            {{$t("device.addNewDeviceTip3")}}
                        </p>
                        <p v-if="isZh">
                            {{$t("device.addNewDeviceTip4")}}
                        </p>
                    </Alert>
                </i-col>
            </Row>

            <Row style="margin: 10px 0">
                <i-col span="6" :offset="4">
                    <i-button style="width: 100%" @click="handleSubmit">{{$t("bgMgr.submit")}}</i-button>
                </i-col>
                <i-col span="6" :offset="1">
                    <i-button style="width: 100%" @click="resetInfo">{{$t("bgMgr.reset")}}</i-button>
                </i-col>
            </Row>
        </div>
        <div class="demo-spin-container" v-show="loading">
            <Spin fix></Spin>
        </div>
    </div>
    <script>
        vueInstanse = new Vue({
            el: "#batchadddevice",
            i18n: utils.getI18n(),
            data: {
                errorTips: "",
                dateOptions: {
                    disabledDate: function(date) {
                        return date && date.valueOf() < Date.now() - 86400000;
                    }
                },
                isZh: isZh,
                timezone: '99',
                calmileageway: '0',
                teltype: '1',
                loading: false,
                idLength: 11,
                iconState: "ios-arrow-down",
                deviceid: "",
                deviceIds: [],
                devicetype: "",
                overduetime: "",
                loginpwd: "",
                loginenable: "1",
                deviceenable: "1",
                groupsList: [],
                deviceTypeList: [],
                groupid: '',
                checkboxObj: {},
                createrToUser: "",
                userlists: [],
                userType: null,
                timeoutIns: null,
                isShowMatchDev: false,
                isOk: false
            },
            methods: {
                handleSubmit: function() {
                    var me = this;
                    var url = myUrls.addDevices();

                    if (!this.isOk) {
                        me.$Message.error(me.$t("device.devIdTips"));
                        return;
                    };
                    var deviceids = this.deviceid.split('\n').filter(function(item) {
                        if (item) {
                            return item
                        }
                    });
                    if (deviceids.length > 500) {
                        me.$Message.error(me.$t("message.addDevice500Tips"));
                        return;
                    }

                    if (this.overduetime == "") {
                        me.$Message.error(me.$t("message.fullComplete"));
                        return;
                    };

                    if (this.devicetype === "") {
                        me.$Message.error(me.$t("message.selectDeviceTtypeTips"));
                        return;
                    }

                    var data = {
                        deviceids: deviceids,
                        devicetype: this.devicetype,
                        expirenotifytime: new Date(this.overduetime).getTime(),
                        loginenable: Number(this.loginenable),
                        deviceenable: Number(this.deviceenable),
                        timezone: Number(this.timezone),
                        calmileageway: Number(this.calmileageway),
                    };

                    if (this.teltype) {
                        data.teltype = Number(this.teltype);
                    }

                    if (this.groupid) {
                        data.groupid = this.groupid;
                    };


                    if (globalUserList.indexOf(this.createrToUser) == -1) {
                        me.$Message.error(me.$t("message.selectCorrectAccount"));
                        return;
                    }


                    if (this.userType < 4) {
                        data.creater = this.createrToUser;
                    } else {
                        data.creater = userName;
                    };

                    this.loading = true;
                    utils.sendAjax(url, data, function(resp) {
                        me.loading = false;
                        if (resp.status == 0) {
                            rootuser = null;
                            isNeedRefresh = true;
                            if (resp.total === resp.success) {
                                me.$Message.success(me.$t("message.addSucc"));
                            } else {
                                me.$Message.error("成功 : " + resp.success + "个,失败 : " + resp.fail + "个");
                                if (resp.errorrecords.length) {
                                    var errorTips = "添加失败的设备号:" + "\n";
                                    resp.errorrecords.forEach(function(item) {
                                        errorTips += item.deviceid + " : " + item.cause + "\n";
                                    });
                                    me.errorTips = errorTips;
                                    me.isOk = false;
                                };
                            }
                        } else if (resp.status == -1) {
                            if (resp.cause !== null && resp.cause.indexOf("token") != -1) {
                                window.location.href = "index.html";
                            } else {
                                me.$Message.error(me.$t("message.addFail"));
                            }
                        } else if (resp.status == 1) {
                            me.$Message.error(me.$t("message.IDRepeat"));
                        } else if (resp.status == 2) {
                            me.$Message.error(me.$t('message.IDError'));
                        } else if (resp.status == 3) {
                            me.$Message.error(me.$t('message.reqFail'));
                        };
                    });
                },
                resetInfo: function() {
                    this.deviceid = "";
                    this.devicetype = 1;
                    // this.overduetime = "";
                    this.loginenable = "1";
                    this.deviceenable = "1";
                    this.groupid = "";

                },

                getDeviceType: function() {
                    var me = this;
                    var deviceTypes = vstore.state.deviceTypes;
                    for (var key in deviceTypes) {
                        var item = deviceTypes[key];
                        if (item) {
                            var label = item.typename;
                            if (item.remark) {
                                label += "(" + (isZh ? item.remark : item.remarken) + ")";
                            }
                            me.deviceTypeList.push({
                                value: item.devicetypeid,
                                label: label
                            });
                        }
                    }

                    me.devicetype = 1;
                },
                getRegularPattern: function(str) {
                    var res = {};
                    // var reg = /^[a-z0-9a-z]{15}/;
                    var reg = new RegExp("^[A-Z0-9a-z]{" + this.idLength + "}");
                    if (reg.test(str)) {
                        if (str.length > this.idLength) {
                            var newStr = str.slice(this.idLength);
                            var i = 0;
                            var charArray = [];
                            while (true) {
                                var char = newStr[i];
                                var isTrue = /[A-Z0-9a-z]/.test(char);
                                if (!isTrue) {
                                    charArray.push(char);
                                } else {
                                    break;
                                }
                                i++;
                            };
                            if (charArray.length > 0) {
                                res.errormsg = "OK";
                                res.content = charArray.join("");
                            } else {
                                res.errormsg = "start id error!";
                                res.content = null;
                            }
                        } else {
                            if (str.length == this.idLength) {
                                res.errormsg = "OK";
                                res.content = str;
                            } else {
                                res.errormsg = "start id error!";
                                res.content = null;
                            }
                        }
                    } else {
                        res.content = null;
                        res.errormsg = "start id error!";
                    }
                    return res;
                },
                matchingDeviceIds: utils.debounce(function(vm, testIds) {
                    var relu = this.getRegularPattern(testIds);
                    if (relu.content && relu.errormsg === 'OK') {
                        var guilv = relu.content;
                        var reg = new RegExp("^[a-z0-9a-z]{" + vm.idLength + "}$");
                        if (reg.test(guilv)) {
                            vm.isOk = true;
                            vm.deviceid = guilv + "\n";
                            vm.errorTips = "总数 : 1";
                        } else {
                            var isOk = true; // 数据是否合法！
                            var textStr = "";
                            var array = testIds.split(guilv);
                            var errorStr = "";
                            var idx = null;
                            for (var i = 0; i < array.length; i++) {
                                var line = array[i];
                                if (reg.test(line)) {
                                    if (array.length - 1 == i) {
                                        textStr += line;
                                    } else {
                                        textStr += line + "\n";
                                    }
                                } else {
                                    idx = i;
                                    if (line.length % vm.idLength === 0) {
                                        var count = line.length / vm.idLength;
                                        var j = 0;
                                        while (count > -1 && j <= count) {
                                            textStr += line.slice(j * vm.idLength, vm.idLength * (j + 1)) + "\n";
                                            j++;
                                            count--;
                                        }
                                    } else {
                                        errorStr = array[i - 1] + guilv + array[i];
                                        if (array[i + 1]) {
                                            errorStr += guilv + array[i + 1];
                                        }
                                        isOk = false;
                                    }
                                }
                            }
                            vm.isOk = isOk;
                            if (isOk) {
                                var newArr = vm.filtered(textStr)
                                var len = newArr.length;
                                vm.deviceid = newArr.join("\n") + "\n";
                                vm.errorTips = "总数  : " + len;
                            } else {
                                vm.errorTips = ("可能在第" + (idx + 1) + "个ID号不合法或者分隔符不一致; \n" + errorStr);
                            }


                        }

                    } else {
                        vm.errorTips = "首个ID号不合法";
                        this.isOk = false;
                    }

                }, 500),
                filtered: function(textStr) {
                    function uniq(array) {
                        var temp = [];
                        for (var i = 0; i < array.length; i++) {
                            if (temp.indexOf(array[i]) == -1) {
                                temp.push(array[i]);
                            }
                        }
                        return temp;
                    }
                    var newArr = [];
                    textStr.split("\n").forEach(function(item) {
                        if (item) {
                            newArr.push(item);
                        }
                    })
                    return uniq(newArr);
                },
                queryGroupsByUserName: utils.debounce(function(userName) {
                    var data = {
                            username: userName
                        },
                        url = myUrls.queryGroupsByUserName(),
                        me = this;
                    utils.sendAjax(url, data, function(resp) {
                        var groupList = [{
                            label: isZh ? '默认组' : 'Default',
                            value: 0
                        }];
                        if (resp.status === 0 && resp.grouplist) {
                            resp.grouplist.forEach(function(group) {
                                groupList.push({
                                    label: group.groupname,
                                    value: group.groupid
                                });
                            })
                        }
                        me.groupid = 0;
                        me.groupsList = groupList;
                    });
                }, 1000)
            },
            watch: {
                idLength: function() {
                    if (this.deviceid == '') return;
                    var exec = /[0-9A-Za-z]/g.exec(this.deviceid);
                    if (exec) {
                        var idx = exec.index;
                        var newText = this.deviceid.slice(idx);
                        this.matchingDeviceIds(this, newText);
                    } else {
                        this.isOk = false;
                        this.errorTips = this.$t('message.deviceIdTips');
                    }
                },
                createrToUser: function(newVal) {
                    if (globalUserList.indexOf(newVal) != -1) {
                        this.groupid = "";
                        this.queryGroupsByUserName(newVal);
                    }
                },
                deviceid: function(newVal) {
                    if (newVal == '') return;
                    var exec = /[0-9A-Za-z]/g.exec(newVal);
                    if (exec) {
                        var idx = exec.index;
                        var newText = newVal.slice(idx);
                        this.matchingDeviceIds(this, newText);
                    } else {
                        this.isOk = false;
                        this.errorTips = this.$t('message.deviceIdTips');
                    }
                },
                devicetype: function(newVal) {
                    var deviceTypeInfo = vRoot.$store.state.deviceTypes[newVal];
                    if (deviceTypeInfo) {
                        this.idLength = deviceTypeInfo.defaultidlength;
                    }
                }
            },
            computed: {
                fontColor: function() {
                    return [this.isOk ? 'succ' : 'error'];
                }
            },
            mounted: function() {
                this.getDeviceType();
                this.createrToUser = userName;

                var userlists = [];
                globalUserList.forEach(function(item) {
                    userlists.push({
                        label: item,
                        value: item,
                    })
                });
                this.userlists = userlists;
                this.overduetime = new Date(Date.now() + 365 * 24 * 3600 * 1000);
                this.userType = vstore.state.userType;
            }
        })
    </script>
</div>